from configparser import ConfigParser
import os
import pymysql
from traceback import print_exc
class ReadConf:
    def __init__(self,file):
        self.config = ConfigParser()
        path = os.path.split(os.path.realpath(__file__))[0] + os.sep + file
        self.config.read(path,encoding='utf-8')
    def get_option(self,option):
        for section in self.config.sections():
            if self.config.has_option(section,option):
                return self.config.get(section,option)

class DB:
    def __init__(self,database):
        self.database = database        # 数据库的名称
        r = ReadConf(str(database)+".ini")       # 配置文件以数据库的名字命名
        self.host = r.get_option(database + "_host")        # ip地址 crmeb_host
        self.user = r.get_option(database + "_user")        # 数据库账号
        self.password = r.get_option(database + "_password")    # 数据库密码
    def connect(self):
        # 创建数据库对象
        self.db = pymysql.connect(host=self.host,password=self.password,user=self.user,database=self.database,cursorclass =pymysql.cursors.DictCursor)
        # 创建游标
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def searchOne(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            return result
        except:
            self.db.rollback()
            print_exc()
            return result
        finally:
            self.close()
    def searchALL(self,sql):
        self.connect()
        result = None
        try:
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except:
            self.db.rollback()
            print_exc()
            return result
        finally:
            self.close()
    def __edit(self,sql):
        self.connect()
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
            print_exc()
        finally:
            self.close()
    def insert(self,sql):
        self.__edit(sql)
    def delete(self,sql):
        self.__edit(sql)
    def update(self,sql):
        return self.__edit(sql)
if __name__ == '__main__':
    # 实例化对象
    d1 = DB('crmeb')
    # 尝试连接一下
    # d1.connect()
    # 查询用户分组表
    print(d1.searchALL('select * from eb_user_group'))







